package com.pioneer.swing.ui;

import java.text.SimpleDateFormat;
import java.awt.Dimension;
import java.awt.BorderLayout;
import java.awt.event.KeyListener;
import java.awt.event.KeyEvent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.event.InternalFrameEvent;
import javax.swing.event.InternalFrameAdapter;
import javax.swing.event.InternalFrameEvent;

import javax.swing.*;
import java.util.*;
import java.io.*;
import java.net.*;
import com.pioneer.util.AppProperties;


/**
 * Title:        Pioneer Metals Application
 * Description:
 * Copyright:    Copyright (c) 2001
 * Company:      Pioneer Metals
 * @author Gary Chen
 * @version 1.0
 */

public class ChatFrame extends JInternalFrame {
	
	public static final int USER_HEADER =  0;
	public static String CHAT_USER = "User";
		
    public JTextArea oldMessages;
	public JScrollPane scrollUsers;
	public JTable userListTable;
	public AllUsersTable userListModel;
	public JTextField messageTextField;
	public JButton sendButton;
	
	private Socket socket;
	private SocketListener socketListener;
	private PrintWriter socketOut;
	private PrintWriter logger;

    public ChatFrame(String host,int port) {
    	super(UIConstants.TITLE_CHAT,true,true);
		this.setName(UIConstants.TITLE_CHAT);

    	JPanel mainPanel=new JPanel(new BorderLayout());
		mainPanel.setBorder(BorderFactory.createEmptyBorder(
                                        15, //top
                                        15, //left
                                        5, //bottom
                                        15) //right
										);
		JPanel centerPanel=new JPanel();
		centerPanel.setLayout(new BorderLayout());
		JPanel topHalf = new JPanel();
		topHalf.setLayout(new BorderLayout());
		oldMessages=new JTextArea(10,40);
		oldMessages.setEditable(false);
		oldMessages.setFocusable(false);
		JScrollPane scrollMessage = new JScrollPane(oldMessages);
		
		topHalf.add(scrollMessage,BorderLayout.CENTER);
		userListTable = new JTable();
		userListTable.setFocusable(false);
		userListModel = new AllUsersTable();
		userListTable.setModel(userListModel);
		userListTable.setPreferredScrollableViewportSize(new Dimension(100,0));
		scrollUsers = new JScrollPane(userListTable);
		
		topHalf.add(scrollUsers,BorderLayout.EAST);
		centerPanel.add(topHalf,BorderLayout.CENTER);
		JPanel bottomHalf = new JPanel();
		bottomHalf.setLayout(new BorderLayout());
		messageTextField = new JTextField();
		messageTextField.addKeyListener(new ChatKeyListener());
		bottomHalf.add(messageTextField,BorderLayout.CENTER);
		//sendButton = new JButton(UIConstants.COMMAND_SEND_MESSAGE);
		//sendButton.addActionListener(new ButtonListener());
		//bottomHalf.add(sendButton,BorderLayout.EAST);
		centerPanel.add(bottomHalf,BorderLayout.SOUTH);
		mainPanel.add(centerPanel);		
	   	this.getContentPane().add(mainPanel,BorderLayout.CENTER);
		
		// *** SETUP LOGGING ***
		
		String userDir = AppProperties.getProperty(AppProperties.USERDIR);	
		
		String dateStr=new SimpleDateFormat("yyyy_MM_dd_HH_mm").format(new Date());	    
		
		String logPath = userDir+File.separator+"chat_log_"+dateStr+".txt";
		System.out.println("Logging to "+logPath);			
    	try {			
			logger = new PrintWriter(new FileWriter(logPath),true);
		}
		catch (IOException ex){
			System.err.println("Error opening chat logger: "+ex.getMessage());
		}		
		
		// *** CONNECT TO SERVER ***
		
		try{
			socket = new Socket(host, port);
			BufferedReader in = new BufferedReader(new InputStreamReader((socket.getInputStream())));
			socketListener = new SocketListener(in);
			socketOut = new PrintWriter(socket.getOutputStream(),true);
		}
		catch (IOException ex){			
			System.err.println("Error opening socket to "+host+" on port "+port+".: "+ex.getMessage());
		}
			
		new Thread(socketListener).start();
		
		// *** GREET SERVER ***
		
		String username = AppProperties.getProperty(AppProperties.USERNAME);
		socketOut.println("USER:"+username);
		socketOut.println("LIST");
		
		// *** ACCEPT CLOSE EVENTS TO DISCONNECT ***
		
		addInternalFrameListener(new WindowCloser());
	}
	
	class ChatKeyListener
	implements KeyListener{
		public void keyReleased(KeyEvent e) {}
		public void keyPressed(KeyEvent e) {}
		
		public void keyTyped(KeyEvent e) {
			char typed=e.getKeyChar();
			if (typed==KeyEvent.VK_ENTER) {
				socketOut.println("MESG:"+messageTextField.getText());
				messageTextField.setText("");			
			}			
		}
	}
		
	
	class SocketListener
	implements Runnable{
		BufferedReader in;
		
		SocketListener(BufferedReader in){
			this.in = in;
		}		
			
		public void run() {
			try {
				if (!socket.isClosed()) {
					String input = null;
					while ((input = in.readLine()) != null) {
						if (input.startsWith("MESG")){
							String temp = input.substring(input.indexOf(":")+1);
							oldMessages.append(temp+"\n");
							logger.println(temp);
						}
						else if (input.startsWith("LIST")){
							String temp = input.substring(input.indexOf(":")+1);
							java.util.StringTokenizer tokenizer = new java.util.StringTokenizer(temp,",");
							List userList = new ArrayList();
							while (tokenizer.hasMoreTokens()) {
								userList.add(tokenizer.nextToken());							
							}
							userListModel.refresh(userList);
							userListTable.revalidate();
							userListTable.repaint();
						}
					    //System.out.println("echo: " + input);
					}
				}
				else {
					System.err.println("Socket is closed.");
				}
			}
			catch (IOException ex){
				System.err.println("Error reading from socket: "+ex.getMessage());				
			}
		}
	}
	
	
	public void fireInternalFrameEvent() {
		fireInternalFrameEvent(InternalFrameEvent.INTERNAL_FRAME_ACTIVATED);
	}
	
	
	class AllUsersTable extends DefaultTableModel {

		//private ManifestDAO dao;
		
	    public AllUsersTable() {
			columnIdentifiers=new Vector();
			columnIdentifiers.add(CHAT_USER);
	    }
	
		public void refresh(List userList)
		{
			dataVector.clear();
			Iterator it = userList.iterator();
			while (it.hasNext()) {
				Vector row=new Vector();
				row.add(it.next());
				dataVector.add(row);
			}

		}
	
		public boolean isCellEditable(int rowIndex,
	                              int columnIndex) {
			return false;
		}
	}
	
	class WindowCloser extends InternalFrameAdapter {
		public void internalFrameClosing(InternalFrameEvent e) {
		    JInternalFrame frame = e.getInternalFrame();		
		    String windowName=frame.getName();
			if (windowName.equals(UIConstants.TITLE_CHAT)) {
				//try {
					socketOut.println("EXIT");
					logger.close();					
				//}
				//catch (IOException ex) {				
					//System.err.println("Error attempting to close chat logger: "+ex.getMessage());
				//}
			}
		}
	}
	
		
	
	
	
    public static void main(String[] args) {
       // ManifestsFrame mainMenuFrame = new ManifestsFrame();
    }


}